package com.julu.o2o.action.system;

import java.util.List;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.ext.jfinal.JFinalBeetlSql;

import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;
import com.julu.o2o.bean.DataObject;
import com.julu.o2o.bean.Paging;
import com.julu.o2o.common.PageIndexHelper;
import com.julu.o2o.common.UrlConstants;
import com.julu.o2o.dao.BlogDao;
import com.julu.o2o.model.Blog;
import com.julu.o2o.util.ArrayUtil;
import com.julu.o2o.util.BeetlSqlDaoUtil;

/**
 * 博客管理
 * @author yangtonggan
 * @date 2016-6-10
 */
public class BlogController extends Controller {
	
	@ActionKey(UrlConstants.URL_BLOG_LIST)	
	public void list(){	
		query();
		render("/system/view/blog_list.html");
	}
	@ActionKey(UrlConstants.URL_BLOG_ADD)	
	public void add(){
		DataObject repJson = new DataObject("添加博客成功");
		try{
			Blog blog = getBean(Blog.class);
			SQLManager dao = JFinalBeetlSql.dao();
			dao.insert(Blog.class, blog);
		}catch(Exception e){
			repJson = new DataObject("添加博客失败");
		}finally{
			renderJson(repJson);
		}
		
	}
	@ActionKey(UrlConstants.URL_BLOG_DEL)
	public void del(){	
		DataObject repJson = new DataObject("删除博客成功");
		try{
			String ids1 = getPara("ids");
			//SQLManager dao = JFinalBeetlSql.dao();	
			String[] ids = ArrayUtil.toArray(ids1);
			BlogDao dao = BeetlSqlDaoUtil.getDao(BlogDao.class);			
			int count = dao.deleteByIds(ids);
			System.out.println("count:"+count);
		}catch(Exception e){
			repJson = new DataObject("删除博客失败");
		}finally{
			renderJson(repJson);
		}
		
		
	}
	@ActionKey(UrlConstants.URL_BLOG_ADD_FORM_UI)
	public void addFormUI(){
		render("/system/view/blog_add_form.html");
	}
	@ActionKey(UrlConstants.URL_BLOG_EDIT_FORM_UI)
	public void editFormUI(){
		try{
			SQLManager dao = JFinalBeetlSql.dao();
			String id = getPara("id");	
			Blog blog = dao.unique(Blog.class, id);
			setAttr("blog", blog);
			render("/system/view/blog_edit_form.html");
		}catch(Exception e){
			DataObject repJson = new DataObject("获取博客失败");
			renderJson(repJson);
		}
	}
	@ActionKey(UrlConstants.URL_BLOG_UPD)
	public void upd(){
		DataObject repJson = new DataObject("更新博客成功");
		try{
			Blog blog = getBean(Blog.class);
			SQLManager dao = JFinalBeetlSql.dao();
			dao.updateById(blog);
		}catch(Exception e){
			repJson = new DataObject("更新博客失败");
		}finally{
			renderJson(repJson);
		}		
	}
	/**
	 * 需要支持带条件的分页查询
	 */
	private void query(){
		SQLManager dao = JFinalBeetlSql.dao();		
		List<Blog> list = dao.all(Blog.class, getParaToInt(0,0), 10);
		long count = dao.allCount(Blog.class);		
		Paging<Blog> p = getPage(list,count);
		setAttr("pageList", list);			
		PageIndexHelper.setPaging(this, p);
		
	}	
	//TODO 待优化list，count
	private Paging<Blog> getPage(List<Blog> list,long count){
		int pageNumber = getParaToInt(0, 1);
		int totalPage = count/Paging.PAGE_SIZE+count%Paging.PAGE_SIZE!=0?1:0;
		Paging<Blog>  page = new Paging<Blog>(list,pageNumber,10,totalPage,(int)count);
		return page;
	}
}
